<?php

namespace app\admin\controller\shop\user;

use app\admin\model\shop\user\Commission;
use think\facade\Db;
use Throwable;
use app\common\controller\Backend;

/**
 * 提现记录
 */
class Withdraw extends Backend
{
    /**
     * Withdraw模型对象
     * @var object
     * @phpstan-var \app\admin\model\shop\user\Withdraw
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array $withJoinTable = ['user'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\shop\user\Withdraw();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit)->each(function ($v){
                if($v->account_type==2){
                    $v->qrcode =$v->account;
                    unset($v->account);
                }
            });;
        $res->visible(['user' => ['nickname']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            if($row['status'] != 10){
                $this->error('该条记录已审核');
            }
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }

                if($data['status'] == 20)
                {
                    //支付宝提现账户
                    if($row['account_type'] ==1){
                        throw new \Exception('支付宝提现暂未开放');
//                        $config = \ba\PayLib::getConfig();
//                        Pay::config($config);
//                        $result = Pay::alipay()->transfer([
//                            'out_biz_no' => $row['id'].$row['user_id'].$row['account'],  // 商户转账唯一订单号
//                            'trans_amount' => $row['received_amount'],  // 转账金额
//                            'product_code' => 'TRANS_ACCOUNT_NO_PWD',  // 产品码，固定值 TRANS_ACCOUNT_NO_PWD 表示无密转账到支付宝账户
//                            'biz_scene' => 'DIRECT_TRANSFER',  // 业务场景，固定值 DIRECT_TRANSFER 表示直连转账
//                            'payee_info' => [
//                                'identity' => $row['account'],  // 收款方账号，这里是支付宝登录号
//                                'identity_type' => 'ALIPAY_LOGON_ID',  // 收款方账号类型，固定值 ALIPAY_LOGON_ID 表示支付宝登录号
//                                'name' => $row['account_name']  // 收款方真实姓名
//                            ],
//                        ]);
//
//                        $res =json_decode($result,true);
//                        if(isset($res['status']) && $res['status']=="SUCCESS"){
//                            $data['out_biz_no'] =$res['out_biz_no']; //流水号
//                            $data['order_id'] =$res['order_id']; //订单号
//                            $data['trans_date'] =$res['trans_date']; //时间
//                            $data['status'] =30; //已到账
//                        }else{
//                            throw new \Exception($res['msg']);
//                        }

                    }else{
                        //同意
                        $data['status'] =30; //已到账
                    }
                }
                if($data['status']  == 40)
                {
                    $model = new Commission();
                    $res = $model->change($row->user_id,$model::TYPE_Withdrawal_Return,$row['amount']);
                    //提现拒绝逻辑
                    if(!$res['status']){
                        throw new \Exception($res['msg']);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {

                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }
}